import React, { Component } from 'react'
import { HomeWrapper, HomeLeft, HomeRight, ScroolTop } from './style'
import Topic from './components/Topic'
import List from './components/List'
import Recommond from './components/Recommond'
import Writer from './components/Writer'
import { actionCreators } from './store'
import { connect } from 'react-redux'

//滚动事件
let eventScroll = null;
class Home extends Component {
  render() {
    return (
      <HomeWrapper>
        <HomeLeft>
          <img
            className="banner-img"
            src="https://upload.jianshu.io/admin_banners/web_images/5010/8e6ff43ffeeadc5deb237a4c1da797b486904373.png"
            alt=""
          />
          <Topic />
          <Recommond />
        </HomeLeft>
        <HomeRight>
          <List />
          <Writer />
        </HomeRight>
        {this.props.showScrollTop ? (
          <ScroolTop  onClick={this.scrollToTop.bind(this)}>
            <p>返回</p>
            <p>顶部</p>
          </ScroolTop>
        ) : null}
      </HomeWrapper>
    )
  }

  bindScrollEvent(e) {
    let scrollTop = document.documentElement.scrollTop;
    if (scrollTop >= 400 && this.props.showScrollTop === false) {
      this.props.changeShowScrollTop(true)
    } else if (scrollTop < 400 && this.props.showScrollTop) {
      this.props.changeShowScrollTop(false)
    }
  }
  componentDidMount() {
    this.props.getHomeData();
    this.bindEvent();
  }
  componentWillUnmount(){
    this.removeEvent()
  }
  bindEvent() {
    eventScroll = this.bindScrollEvent.bind(this);
    window.addEventListener('scroll', eventScroll);
  }
  removeEvent(){
    window.removeEventListener("scroll",eventScroll);
  }
  scrollToTop(){
    this.customScrollTop(1000);
  }
  
  customScrollTop(time){
    let top = document.documentElement.scrollTop;
    const spacingTime = 20;
    const count = time/spacingTime;
    const distance = top/count;
    
    const tim = setInterval(()=>{
      top-=distance
      document.documentElement.scrollTop = top;
      if(top<=0){
        clearInterval(tim);
      }
    })
  }
}

const mapState = (state) => {
  return {
    showScrollTop: state.getIn(['home', 'showScrollTop']),
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    async getHomeData() {
      dispatch(actionCreators.getHomeData())
    },
    changeShowScrollTop(value) {
      dispatch(actionCreators.changeShowScrollTop(value))
    },
  }
}

export default connect(mapState, mapDispatchToProps)(Home)
